import com.picture.server.Role
import com.picture.server.User
import com.picture.server.UserRole
import com.picture.server.Contact
import org.springframework.security.oauth2.provider.BaseClientDetails

class BootStrap {

    def clientDetailsService

    def init = { servletContext ->

        registerUsersAndRoles()
        registerOAuthClient()
    }
    def destroy = {
    }

    private void registerUsersAndRoles() {
        def adminRole = new Role(authority: 'ROLE_ADMIN').save(flush: true)
        def adminUser = new User(username: 'admin', enabled: true, password: '123456')
        adminUser.save(flush: true)
        UserRole.create adminUser, adminRole, true

        def userRole = new Role(authority: 'ROLE_USER').save(flush: true)
        def regularUser = new User(username: 'user', enabled: true, password: '123456')
        def contacts = [
                new Contact(name: "Victor", email: "victor.manuel.toto@gmail.com", user: regularUser),
                new Contact(name: "Nicolas", email: "nicomorales1@gmail.com", user: regularUser),
                new Contact(name: "Santiago", email: "gringotumadre@gmail.com", user: regularUser),
                new Contact(name: "Diego", email: "dmascialino@gmail.com", user: regularUser)
        ]
        regularUser.contacts = contacts as Set
        regularUser.save(flush: true)
        UserRole.create regularUser, userRole, true
    }

    // Register an example oauth client
    private void registerOAuthClient() {
        def client = new BaseClientDetails()
        client.clientId = "clientId"
        client.clientSecret = "clientSecret"
        client.authorizedGrantTypes = ["authorization_code", "refresh_token", "client_credentials", "password", "implicit"]

        // Set the full contents of the client details service store to the newly created client
        clientDetailsService.clientDetailsStore = [
                // Map of client ID to the client details instance
                "clientId": client
        ]
    }

}
